package org.devops


//封装HTTP请求
def HttpReq(reqType,reqUrl,reqBody){
    //def apiServer = "https://192.168.1.200:6443/apis/apps/v1"
    //k8s api 地址
    def apiServer = "https://172.16.1.122:6443"
    //withCredentials([string(credentialsId: 'kubernetes-token', variable: 'kubernetestoken')]) {
    withCredentials([string(credentialsId: '69710fb4-0423-4055-9a25-20c4ad5c1ec9', variable: 'kubernetestoken')]) {
    //result = httpRequest customHeaders: [[maskValue: true, name: 'Authorization', value: "Bearer ${kubernetestoken}"],
    result = httpRequest customHeaders: [[maskValue: true, name: 'Authorization', value: "Bearer ${kubernetestoken}"],
                                           [maskValue: false, name: 'Content-Type', value: 'application/yaml'], 
                                           [maskValue: false, name: 'Accept', value: 'application/yaml']],  
                httpMode: reqType, 
                consoleLogResponseBody: true,
                ignoreSslErrors: true, 
                requestBody: reqBody,
                url: "${apiServer}/${reqUrl}"
                //quiet: true
    }
    return result
}

//新建Service
def CreateServices(nameSpace,ServiceName,ServiceBody){
    apiUrl = "/api/v1/namespaces/${nameSpace}/services/"
    response = HttpReq('POST',apiUrl,ServiceBody)
    println(response)
}

//删除Service
def DeleteServices(nameSpace,serviceName){
    apiUrl = "/api/v1/namespaces/${nameSpace}/services/${serviceName}"
    response = HttpReq('DELETE',apiUrl,deplyBody)
    println(response)
}

//获取Service
def GetServices(nameSpace,serviceName){
    apiUrl = "/api/v1/namespaces/${nameSpace}/services/${serviceName}"
    response = HttpReq('GET',apiUrl,'')
    return response
}

//新建Deployment
def CreateDeployment(nameSpace,deployName,deplyBody){
    apiUrl = "/apis/apps/v1/namespaces/${nameSpace}/deployments/"
    response = HttpReq('POST',apiUrl,deplyBody)
    println(response)
}

//删除deployment
def DeleteDeployment(nameSpace,deployName){
    apiUrl = "/apis/apps/v1/namespaces/${nameSpace}/deployments/${deployName}"
    response = HttpReq('DELETE',apiUrl,deplyBody)
    println(response)
}

//更新Deployment
def UpdateDeployment(nameSpace,deployName,deplyBody){
    apiUrl = "/apis/apps/v1/namespaces/${nameSpace}/deployments/${deployName}"
    response = HttpReq('PUT',apiUrl,deplyBody)
    println(response)
}

//获取Deployment
def GetDeployment(nameSpace,deployName){
    apiUrl = "/apis/apps/v1/namespaces/${nameSpace}/deployments/${deployName}"
    try{
        response = HttpReq('GET',apiUrl,'')
    } catch (Exception e){
        return trycatch(e)
    }
    return response
}

//异常捕获
def trycatch(e){
    println "发现异常：" + e
	println e.getCause()
	println e.printStackTrace()
    return '0'
}
